package com.zrkizzy.module.content.command.impl;

import com.zrkizzy.common.models.dto.blog.article.command.ArticleCommandDTO;
import com.zrkizzy.content.facade.service.article.IArticleTagsService;
import com.zrkizzy.module.content.command.ArticleCommand;
import com.zrkizzy.module.content.exception.BlogErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文章标签关联命令实现类
 *
 * @author zhangrongkang
 * @since 2023/10/9
 */
@Service
public class ArticleTagsCommand implements ArticleCommand {

    @Autowired
    private IArticleTagsService articleTagsService;

    /**
     * 添加文章相关内容命令
     *
     * @param articleCommandDTO 文章命令数据传输对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeAddArticle(ArticleCommandDTO articleCommandDTO) {
        // 添加失败则抛出异常
        if (!articleTagsService.insert(articleCommandDTO.getTagIds(), articleCommandDTO.getArticleId())) {
            throw BlogErrorCode.ARTICLE_TAGS_ASSOCIATION_INSERT_ERROR.exception();
        }
    }

    /**
     * 更新文章相关命令
     *
     * @param articleCommandDTO 文章命令数据传输对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeUpdateArticle(ArticleCommandDTO articleCommandDTO) {
        if (!articleTagsService.update(articleCommandDTO.getTagIds(), articleCommandDTO.getArticleId())) {
            // 更新失败则抛出异常
            throw BlogErrorCode.ARTICLE_TAGS_ASSOCIATION_UPDATE_ERROR.exception();
        }
    }

    /**
     * 删除文章相关命令
     *
     * @param articleCommandDTO 文章命令数据传输对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeDeleteArticle(ArticleCommandDTO articleCommandDTO) {
        articleTagsService.deleteByArticleId(articleCommandDTO.getArticleId());
    }
}
